package com.example.activemq.controller;

import com.example.activemq.config.QueueConfig;
import com.example.activemq.config.TopicConfig;
import com.example.activemq.pojo.MessagePojo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.jms.Destination;
import javax.jms.Queue;
import javax.jms.Topic;
import java.time.LocalDateTime;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2021/4/2 23:12
 * @Description TODO
 */
@RestController
@Slf4j
@RequestMapping(value = "/send")
public class ProducerController {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    /**
     * @Description:   注入制定的队列 {@link QueueConfig#queue()}
     * @Author: LiYuhang
     * @return
     */
    @Autowired
    private Queue queue;
    /**
     * @Description:   注入制定的队列 {@link TopicConfig#topic()}
     * @Author: LiYuhang
     * @return
     */
    @Autowired
    private Topic topic;

    //http://localhost:81/send/queue/test/
    @PostMapping("/queue/test")
    public String sendQueue(@RequestBody String str) {

        this.sendMessage(this.queue, str);
        return "success";
    }

    @PostMapping("/topic/test")
    public String sendTopic(@RequestBody String str) {
        this.sendMessage(this.topic, str);
        return "success";
    }

    // 发送消息，destination是发送到的队列，message是待发送的消息
    private void sendMessage(Destination destination,final String messageContent){
        jmsMessagingTemplate.convertAndSend(destination, new MessagePojo(messageContent,LocalDateTime.now()));
    }
}
